<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/11/5
 * Time: 13:56
 */

namespace app\admin\controller;


use think\Db;

class Member extends Base
{
    /**
     * 首页展示
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $regist_start_time = input('regist_start_time'); // 注册开始时间
            $regist_end_time = input('regist_end_time'); // 注册结束时间
            $login_start_time = input('login_start_time'); // 登录开始时间
            $login_end_time = input('login_end_time'); // 登录结束时间
            $user_gender = input('user_gender');
            $user_role = input('user_role');
            $user_keyword = input('user_keyword');
            $user_status = input('user_status');
    
            $where = [];
            if(isset($regist_start_time) && $regist_start_time != '' && isset($regist_end_time) && $regist_end_time != ''){
                $where['user_time'] = ['between', [$regist_start_time, $regist_end_time]];
            }
            if(isset($regist_start_time) && $regist_start_time != '' && isset($regist_end_time) && $regist_end_time == ''){
                $where['user_time'] = ['>', $regist_start_time];
            }
            if(isset($regist_start_time) && $regist_start_time == '' && isset($regist_end_time) && $regist_end_time != ''){
                $where['user_time'] = ['<', $regist_end_time];
            }
            if(isset($login_start_time) && $login_start_time != '' && isset($login_end_time) && $login_end_time != ''){
                $where['user_time'] = ['between', [$login_start_time, $login_end_time]];
            }
            if(isset($login_start_time) && $login_start_time != '' && isset($login_end_time) && $login_end_time == ''){
                $where['user_time'] = ['>', $login_start_time];
            }
            if(isset($login_start_time) && $login_start_time == '' && isset($login_end_time) && $login_end_time != ''){
                $where['user_time'] = ['<', $login_end_time];
            }
            if(isset($user_gender) && $user_gender != ''){
                $where['user_gender'] = $user_gender;
            }
            if(isset($user_role) && $user_role != ''){
                if($user_role == 1){
                    $where['user_role'] = 1;
                }elseif($user_role == 2){
                    $where['user_role'] = ['IN', '2,3'];
                }else{
                    $where['user_role'] = ['IN', '4,5,6'];
                }
            }
            if(isset($user_status) && $user_status != ''){
                $where['user_status'] = $user_status;
            }
            if(isset($user_keyword) && $user_keyword != ''){
                $where['user_id|user_phone'] = ['like', '%' . $user_keyword . '%'];
            }
            
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('u_user')
                ->join('up_area ua1', 'ua1.district_id = user_sheng', 'left')
                ->join('up_area ua2', 'ua2.district_id = user_shi', 'left')
                ->join('up_area ua3', 'ua3.district_id = user_qu', 'left')
                ->where($where)
                ->count();// 获取总条数
            $count2 = Db::name('u_user')
                ->join('up_area ua1', 'ua1.district_id = user_sheng', 'left')
                ->join('up_area ua2', 'ua2.district_id = user_shi', 'left')
                ->join('up_area ua3', 'ua3.district_id = user_qu', 'left')
                ->where($where)
                ->column('user_id');// 获取总条数
            $lists = Db::name('u_user')
                ->join('up_area ua1', 'ua1.district_id = user_sheng', 'left')
                ->join('up_area ua2', 'ua2.district_id = user_shi', 'left')
                ->join('up_area ua3', 'ua3.district_id = user_qu', 'left')
                ->field('user_id, user_image, user_username, user_phone, user_email, user_gender, 
                user_status, user_birthday, user_time, user_last_login_time, user_role, ua1.district sheng, 
                ua2.district shi, ua3.district qu')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('user_time desc')
                ->select();
            foreach($lists as $k => $v){
                $lists[$k]['district'] = $v['sheng'] . $v['shi'] . $v['qu'];
            }
            $str = '';
            if($count2){
                $str = implode($count2,',');
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'count2' => $str, 'data' => $lists]);
        }
        return $this->fetch();
    }
    
    /**
     * 用户详情
     * @return mixed
     */
    public function userDetail(){
        $user_id = input('user_id');
        $user = Db::table('up_u_user')
            ->join('up_area ua1', 'ua1.district_id = user_sheng', 'left')
            ->join('up_area ua2', 'ua2.district_id = user_shi', 'left')
            ->join('up_area ua3', 'ua3.district_id = user_qu', 'left')
            ->where('user_id', $user_id)
            ->field('user_id, user_image, user_username, user_phone, user_email, user_gender, 
                user_status, user_birthday, user_time, user_last_login_time, user_role, ua1.district sheng, 
                ua2.district shi, ua3.district qu')
            ->find();
        
        // 我买的订单
        $order = Db::table('up_goods_order')
            ->where('order_buy_user_id', $user_id)
            ->where('order_status', 'IN', '4,5,7,9')
            ->field('order_pay_price')
            ->select();
        $total_order_num = 0; // 总订单数
        $total_order_price = 0; // 总订单金额
        if($order){
            $total_order_num = count($order);
            foreach($order as $k => $v){
                $total_order_price += $v['order_pay_price'];
            }
        }
        $user['total_order_num'] = $total_order_num;
        $user['total_order_price'] = $total_order_price;
        $this->assign('user', $user);
        return $this->fetch('member/userdetail');
    }
    
    /**
     * 禁用
     * @return \think\response\Json
     */
    public function userFreeze(){
        $user_id = input('id');
        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_status', 2);
        if($res){
            return json(['code' => 200, 'msg' => '禁用成功']);
        }else{
            return json(['code' => 100, 'msg' => '禁用失败']);
        }
    }
    
    /**
     * 启用
     * @return \think\response\Json
     */
    public function userStartUsing(){
        $user_id = input('id');
        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_status', 1);
        if($res){
            return json(['code' => 200, 'msg' => '启用成功']);
        }else{
            return json(['code' => 100, 'msg' => '启用失败']);
        }
    }
    
    /**
     * 升级为画师
     * @return \think\response\Json
     */
    public function upPainter(){
        $user_id = input('id');
        Db::startTrans();
        try{
            // 修改用户角色
            Db::table('up_u_user')
                ->where('user_id', $user_id)
                ->update([
                    'user_role' => 2,
                    'user_painter_time' => date('Y-m-d H:i:s')
                ]);
            // 如果没有店铺，插入店铺表
            $have = Db::table('up_shop')->where('shop_user_id', $user_id)->find();
            if(!$have){
                Db::table('up_shop')->insert([
                    'shop_user_id' => $user_id,
                    'shop_time' => date('Y-m-d H:i:s')
                ]);
            }
            Db::commit();
            return json(['code' => 200, 'msg' => '操作成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['code' => 100, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 升级为高级画师
     * @return \think\response\Json
     */
    public function upHighPainter(){
        $user_id = input('id');
        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_role', 4);
        if($res){
            return json(['code' => 200, 'msg' => '设置成功']);
        }else{
            return json(['code' => 100, 'msg' => '设置失败']);
        }
    }
    
    /**
     * 导出
     * @return \think\response\Json
     */
    public function outExcel(){
        set_time_limit(0);
        $user_ids = input('ids');
        if($user_ids == ''){
            return json(['code' => 100, 'msg' => '请选择要操作的用户']);
        }
        $lists = Db::name('u_user')
            ->join('up_area ua1', 'ua1.district_id = user_sheng', 'left')
            ->join('up_area ua2', 'ua2.district_id = user_shi', 'left')
            ->join('up_area ua3', 'ua3.district_id = user_qu', 'left')
            ->where('user_id', 'IN', $user_ids)
            ->field('user_id, user_username, user_phone, user_email, user_gender, user_status, 
            user_birthday, user_time, user_last_login_time, user_role, ua1.district sheng, ua2.district shi, 
            ua3.district qu')
            ->order('user_time desc')
            ->select();
        foreach($lists as $k => $v){
            // 性别
            if($v['user_gender'] == 1){
                $lists[$k]['gender'] = '男';
            }elseif($v['user_gender'] == 2){
                $lists[$k]['gender'] = '女';
            }else{
                $lists[$k]['gender'] = '未知';
            }
            // 手机号
            $lists[$k]['user_phone'] = "\t".$v['user_phone']."\t";
            // 城市
            $lists[$k]['district'] = $v['sheng'] . $v['shi'] . $v['qu'];
            // 用户状态
            $lists[$k]['user_status'] = $v['user_status'] == 1 ? '正常' : '已禁用';
            // 用户分类
            if($v['user_role'] == 1){
                $lists[$k]['user_role'] = '普通用户';
            }elseif($v['user_role'] == 2 || $v['user_role'] == 3){
                $lists[$k]['user_role'] = '画师';
            }else{
                $lists[$k]['user_role'] = '高级画师';
            }
            // 处理特殊字符串
            $user_name = json_encode($v['user_username']);
            $name = preg_replace("/\\\u[ed][0-9a-f]{3}\\\u[ed][0-9a-f]{3}/", "*", $user_name);//将特殊字符串替换成*
            $lists[$k]['user_username'] = json_decode($name);
            // 订单
            $order = Db::table('up_goods_order')
                ->where('order_buy_user_id', $v['user_id'])
                ->where('order_status', 'IN', '4,5,7,9')
                ->field('order_pay_price')
                ->select();
            $total_order_num = 0; // 总订单数
            $total_order_price = 0; // 总订单金额
            if($order){
                $total_order_num = count($order);
                foreach($order as $kk => $vv){
                    $total_order_price += $vv['order_pay_price'];
                }
            }
            $lists[$k]['total_order_num'] = $total_order_num;
            $lists[$k]['total_order_price'] = $total_order_price;
        }
        $cellname = [
            ['user_id', '用户ID', 15, 'LEFT'],
            ['user_username', '昵称', 15, 'LEFT'],
            ['user_phone', '手机号', 20, 'LEFT'],
            ['gender', '性别', 10, 'LEFT'],
            ['user_birthday', '出生日期', 15, 'LEFT'],
            ['user_email', '邮箱', 30, 'LEFT'],
            ['user_role', '用户分类', 15, 'LEFT'],
            ['user_status', '用户状态', 15, 'LEFT'],
            ['district', '城市', 25, 'LEFT'],
            ['user_time', '注册时间', 20, 'LEFT'],
            ['user_last_login_time', '最后登录时间', 20, 'LEFT'],
            ['total_order_num', '订单总数量', 20, 'LEFT'],
            ['total_order_price', '订单总金额', 20, 'LEFT']
        ];
        $res = exportExcel('用户列表','Members',$cellname,$lists);
        return json($res);
    }
}